const mongoose = require('mongoose')
const Router = require('koa-router')
const CommentRouter = new Router()
const Comment = mongoose.model('Comment')
const ArticleSchema = mongoose.model('Article')

CommentRouter.get('/get', async (ctx) => {
  try {
    const { articleId } = ctx.request.query
    const res = await Comment.find({articleId}).sort({createTime: -1}).exec()
    ctx.body = {
      code: 200,
      message: res
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

CommentRouter.post('/send', async (ctx) => {
  try {
    const { articleId } = ctx.request.body
    const CommentSchema = new Comment(ctx.request.body)
    await CommentSchema.save()
    const count = await Comment.find({articleId}).countDocuments()
    await ArticleSchema.updateOne({_id: articleId}, {$set: {commentCount: count}})
    ctx.body = {
      code: 200,
      message: '提交成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

module.exports = CommentRouter
